<?php

// +----------------------------------------------------------------------
// | 权限组控制器
// +----------------------------------------------------------------------
// | Copyright (c) 2015-2024 http://www.yicmf.com, All rights reserved.
// +----------------------------------------------------------------------
// | Author: 微尘 <yicmf@qq.com>
// +----------------------------------------------------------------------

namespace app\controller\pos\admin;

use app\model\pos\PosOrder as PosOrderModel;
use app\event\pos\PosOrder as PosOrderEvent;
use app\model\pos\Pos as PosModel;
use app\model\ucenter\User as UserModel;
use yicmf\builder\Edit;
use yicmf\builder\Table;
use app\controller\admin\Common;

class PosOrder extends Common
{
    protected function initialize()
    {
        parent::initialize();
    }

    public function _filter()
    {
        $where = [];
        $field = $this->request->param('field/a');
        if (!isset($field['status'])) {

            $where[] = ['status', '>', 0];
        }
        return $where;
    }

    public function index()
    {
        $statusOptions = [
            [
                'id' => 0,
                'value' => '已取消'
            ],
            [
                'id' => 1,
                'value' => '待支付'
            ],
            [
                'id' => 2,
                'value' => '待发货'
            ],
            [
                'id' => 3,
                'value' => '待确认'
            ],
            [
                'id' => 5,
                'value' => '已完成'
            ]
        ];
        $where = $this->_filter();
        // 显示页面
        $builder = new Table();
        $builder->model(PosOrderModel::class)
            ->where($where)
            ->order('id DESC')
//                ->suggest('高等级可以对低等级用户进行操作或者授权')
//            ->searchUser('下单用户')
            ->searchSelect('status', '订单状态', $statusOptions)
            ->searchTextLike('sn', '订单号')
//            ->buttonUpdate('update?type=0')
            ->keyId()
            ->keyText('sn', '订单号')
            ->keyText('name', '订单名称')
            ->keyTab('number', '包POS个数', '/pos/admin/Pos/index?order_sn={{d.sn}}')
//            ->keyText('effective_number', '有效POS个数')
//            ->keyText('good_amount', 'POS金额')
            ->keyText('address_info_text', '地址', false, 200)
            ->keyText('amount', '订单金额')
//            ->keyText('remark', '备注')
            ->keyUser('user_id', '下单用户')
            ->keyClosure('邀请人', function ($data) {
                $pid = UserModel::where('id', $data['user_id'])->value('pid');
                if ($pid) {
                    $user = UserModel::where('id', $pid)->find();
                    if ($user) {
                        return $user['nickname'] . '(' . $user['id'] . ')';
                    }
                }
                return '-';
            })
            ->keyTime('pay_time', '支付时间')
//            ->keyTime('cancel_time','取消时间')
//				->keyText('description', '描述')
            ->keyCreateTime('下单时间')
            ->keyStatus(['已取消', '待支付', '待发货', '待确认', '已完成', '已完成'])
//            ->quickUpdate(['title','description'])
            ->actionView('view?id={$id}', '详情', function ($data) {
                return true;
            })
            ->actionUpdate('pay?id={$id}', '支付', [1])
            ->actionUpdate('send?id={$id}', '发货', [2]);
//            ->actionDelete();
//            ->actionForbid('forbid?id={$id}', '禁用', function ($data) {
//                return 1 == $data['status'] && 1 < $data['id'];
//            });
        return $builder->fetch();
    }

    public function find()
    {


        $ids = $this->request->param('__id');

        $count = PosModel::where('id', 'in', $ids)->whereNull('user_id')->where('status', 1)->count();

        $ids = PosModel::where('id', 'in', $ids)->whereNull('user_id')->where('status', 1)->column('id');
        $where = $this->_filter();
//        $where[] = ['number', '>', $count];
        $where[] = ['status', '=', 2];
        // 显示页面
        $builder = new Table();
        $builder->model(PosOrderModel::class)
            ->where($where)
            ->order('id DESC')
            ->searchDateTimeRange('create_time', '下单时间')
            ->keyId()
//            ->keyText('sn', '订单号', false, '150')
//            ->keyText('name', '订单名称')
            ->keyText('number', '包POS个数')
//            ->keyText('effective_number', '有效POS个数')
//            ->keyText('good_amount', 'POS金额')
            ->keyText('amount', '订单金额')
//            ->keyText('remark', '备注')
            ->keyUser('user_id', '用户')
            ->keyTime('pay_time', '支付时间')
//            ->keyTime('cancel_time','取消时间')
//				->keyText('description', '描述')
//            ->keyUpdateTime()
//            ->keyStatus(['已取消', '待支付', '待发货', '待确认', '已完成'])
//            ->quickUpdate(['title','description'])
            ->actionToCheck('cart?id={$id}&pos_ids=' . implode(',', $ids), '临存', [2], '临时保存关联30分钟')
            ->actionUpdate('send?id={$id}&pos_ids=' . implode(',', $ids), '发货', [2], true);
//            ->actionDelete();
//            ->actionForbid('forbid?id={$id}', '禁用', function ($data) {
//                return 1 == $data['status'] && 1 < $data['id'];
//            });
        return $builder->fetch();
    }

    public function cart()
    {

        $order_id = $this->request->param('id');
        $ids = explode(',', $this->request->param('pos_ids'));
        if (cache('order_cart_' . $order_id)) {
            $idss = explode(',', cache('order_cart_' . $order_id));
            $ids = array_merge($ids, $idss);
            $ids = array_unique($ids);
        }
        cache('order_cart_' . $order_id, implode(',', $ids), 30 * 60);
        $this->_returnSuccess('关联');


    }

    public function view()
    {
        $order = PosOrderModel::where('id', $this->request->param('id'))->find();
        if (!$order) {
            $this->_returnError('信息不存在');
        }

        $this->assign('order', $order);
//        return $this->fetch();
        return $this->fetch('detail');
    }

    public function update()
    {
        if ($this->request->isPost()) {
            try {
                if ($this->request->param('id')) {
                    $group = PosOrderModel::where('id', $this->request->param('id'))->where('store_id', $this->store['id'])->find();
                    if (!$group) {
                        throw new Exception('权限不存在');
                    }
                    $group['title'] = $this->request->param('title');
                    $group['description'] = $this->request->param('description');
                    $data['message'] = '保存成功';
                    $group->save();
                } else {
                    // 新增
                    $group['module'] = 'im';
                    $group['store_id'] = $this->store['id'];
                    $group['title'] = $this->request->param('title');
                    $group['description'] = $this->request->param('description');

                    PosOrderModel::create($group);
                    $data['message'] = '新增成功';
                }

                $data['code'] = 0;
            } catch (Exception $e) {
                $data['code'] = 1;
                $data['message'] = $e->getMessage();
            }
            if (0 === $data['code']) {
                $this->_returnSuccess($data['message']);
            } else {
                $this->_returnError($data['message'], false);
            }
        } else {
            // 同步节点与菜单
            if ($this->request->param('id')) {
                $group_id = $this->request->param('id');
                $data = PosOrderModel::where('id', $group_id)->where('store_id', $this->store['id'])->find();
                if (!$data) {
                    $this->_returnError('标签不存在');
                }
            } else {
                $data = [];
                $data['store_id'] = $this->store['id'];
            }
            $builder = new Edit();
            $builder->title('标签管理')->keyHidden('store_id')
                ->keyTextInline('title', '标签名称', '')
                ->keyTextArea('description', '描述信息')
                ->data($data)
                ->buttonSubmit();
            return $builder->fetch();
        }
    }

    public function send()
    {
        if ($this->request->isPost()) {
            $event = new PosOrderEvent();
            $data = $event->send($this->request->post(), $this->user);
            if (0 === $data['code']) {
                $this->_returnSuccess($data['message']);
            } else {
                $this->_returnError($data['message'], false);
            }
        } else {
            // 同步节点与菜单
            if ($this->request->param('id')) {
                $group_id = $this->request->param('id');
                $data = PosOrderModel::where('id', $group_id)->where('status', 2)->find();
                if (!$data) {
                    $this->_returnError('标签不存在');
                }
            } else {
                $data = [];
            }
            $data['pos_ids'] = $this->request->param('pos_ids');
            $builder = new Edit();
            $builder->title('发货')
                ->keyLabel('number', '包POS个数');

//            halt($data['pos_vips']->toArray());
            $text = '';
            foreach ($data['pos_vips'] as $index => $item) {
                $text .= "【" . $item['title'] . '*' . $item['number'] . "】";
            }
            $data['pos_vip_info'] = $text;
            $builder->keyLabel('pos_vip_info', '包含套餐包')
                ->keyHidden('pos_ids')
                ->keyRadio('send_type', '发货方式', ['自提', '快递'], null, 0, null, true)
                ->keyLabel('address_info_text', '地址', '')
                ->keyTextInline('express_name', '快递公司', '')
                ->keyTextInline('express_sn', '快递单号', '')
                ->setTrigger('send_type', '1', 'express_name,express_sn')
                ->setTrigger('send_type', '0', '')
                ->data($data)
                ->buttonSubmit(null, '确认发货');
            return $builder->fetch();
        }
    }


    public function pay()
    {
        if ($this->request->isPost()) {
            $event = new PosOrderEvent();
            // $data = $event->pay($this->request->post(), $this->user);
            $data = $event->adminPay2($this->request->post(), $this->user);
            if (0 === $data['code']) {
                $this->_returnSuccess($data['message']);
            } else {
                $this->_returnError($data['message'], false);
            }
        } else {
            // 同步节点与菜单
            if ($this->request->param('id')) {
                $order = PosOrderModel::where('id', $this->request->param('id'))->where('status', 1)->find();
                if (!$order) {
                    $this->_returnError('订单不存在');
                }
                $data['id'] = $order['id'];
                $data['pay_sn'] = $order['sn'];
            } else {

                $this->_returnError('订单不存在', false);
            }
            $builder = new Edit();

            $builder->keyHidden('id')
                ->data($data)
                ->buttonSubmit(null, '确认挂账');
            return $builder->fetch();
        }
    }


}
